﻿using System;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Resources;
using System.IO;
using System.Collections.Generic;
using System.Windows.Media;

namespace Coco.Library.Helpers
{
    public class XamlHelper
    {
        public T LoadXaml<T>(string uri)
        {
            try
            {
                string xaml = string.Empty;
                StreamResourceInfo sri = Application.GetResourceStream(new Uri(uri, UriKind.RelativeOrAbsolute));
                using (StreamReader sr = new StreamReader(sri.Stream))
                {
                    xaml = sr.ReadToEnd();
                }
                T shape = (T)XamlReader.Load(xaml);
                return shape;
            }
            catch
            {
                return default(T);
            }
        }

        public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
        {
            if (depObj != null)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
                {
                    DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                    if (child != null && child is T)
                    {
                        yield return (T)child;
                    }

                    foreach (T childOfChild in FindVisualChildren<T>(child))
                    {
                        yield return childOfChild;
                    }
                }
            }
        }
    }
}
